﻿using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
using System.Windows.Controls;
using KinectDwa.Parsers.Helpers;

namespace Microsoft.Samples.Kinect.WpfViewers
{

    public partial class KinectHandViewer : ImageViewer
    {

        private const int RedIndex = 2;
        private const int GreenIndex = 1;
        private const int BlueIndex = 0;
        private static readonly int Bgr32BytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel + 7) / 8;

        private static byte[] depthFrame32;
        private WriteableBitmap outputHandBitmap;
        private Image handImage;

        public KinectHandViewer()
        {
            InitializeComponent();

            handImage = kinectHandmage;

            //handImage.Width = HandGestureReader.PicWidth * 3;
            //handImage.Height = HandGestureReader.PicHeight * 3;
        }

        public void ShowHand(short[] array, int width, int height)
        {
            try
            {
                depthFrame32 = new byte[width * height * Bgr32BytesPerPixel];

                byte[] convertedDepthBits = ConvertHandFrame(array);

                outputHandBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr32, null);

                handImage.Source = outputHandBitmap;

                outputHandBitmap.WritePixels(new Int32Rect(0, 0, width, height), convertedDepthBits, width * Bgr32BytesPerPixel, 0);
            }
            catch { }
        }

        private static byte[] ConvertHandFrame(short[] depthFrame)
        {
            for (int i16 = 0, i32 = 0; i16 < depthFrame.Length && i32 < depthFrame32.Length; i16++, i32 += 4)
            {
                if (depthFrame[i16] != 0)
                {
                    depthFrame32[i32 + RedIndex] = (byte)(255 - depthFrame[i16]);
                    depthFrame32[i32 + GreenIndex] = (byte)(255 - depthFrame[i16]);
                    depthFrame32[i32 + BlueIndex] = (byte)(255 - depthFrame[i16]);
                }
            }

            return depthFrame32;
        }


        protected override void OnKinectChanged(KinectSensor oldKinectSensor, KinectSensor newKinectSensor)
        {
            if (oldKinectSensor != null)
            {
                handImage.Source = null;
            }

        }
     
    }
}
